<template>
    <div class="h-80 bg-gray-50 py-1">
        <div class="max-w-full h-full px-1">
            <!-- 标题 -->
            <div class="text-center mb-8">
                <h1 class="text-3xl font-bold text-gray-900 mb-1">字符串生成器</h1>
                <p class="text-gray-600">生成指定格式的随机字符串</p>
            </div>

            <div class="grid grid-cols-5 gap-3">
                <!-- 左侧：配置表单 -->
                <div class="col-span-3" style="height: 560px;">
                    <el-card class="mb-8 shadow-lg">
                        <template #header>
                            <div class="flex items-center justify-between">
                                <h2 class="text-xl font-semibold text-gray-800">生成新字符串</h2>
                            </div>
                        </template>

                        <el-form :model="form" label-width="120px" label-position="left">
                            <!-- 字符串长度 -->
                            <el-form-item label="字符串长度" required>
                                <el-input-number v-model="form.length" :min="1" :max="65535" placeholder="请输入长度"
                                    class="w-full" />
                            </el-form-item>

                            <!-- 字符类型 -->
                            <el-form-item label="字符类型" required>
                                <el-select v-model="form.char_type" placeholder="请选择字符类型" class="w-full">
                                    <el-option v-for="type in charTypes" :key="type.value" :label="type.label"
                                        :value="type.value" />
                                </el-select>
                            </el-form-item>

                            <!-- 自定义字符集 -->
                            <el-form-item v-if="form.char_type === 'custom'" label="自定义字符" required>
                                <el-input v-model="form.custom_chars" placeholder="请输入自定义字符集" clearable
                                    class="w-full" />
                                <div class="text-sm text-gray-500 mt-2">
                                    请输入您想要包含在生成字符串中的字符
                                </div>
                            </el-form-item>

                            <!-- 前缀 -->
                            <el-form-item label="前缀">
                                <el-input v-model="form.prefix" placeholder="请输入前缀" clearable class="w-full"
                                    :maxlength="50" />
                                <div class="text-sm text-gray-500 mt-2">
                                    前缀长度会被计入总长度
                                </div>
                            </el-form-item>

                            <!-- 后缀 -->
                            <el-form-item label="后缀">
                                <el-input v-model="form.suffix" placeholder="请输入后缀" clearable class="w-full"
                                    :maxlength="50" />
                                <div class="text-sm text-gray-500 mt-1">
                                    后缀长度会被计入总长度
                                </div>
                            </el-form-item>

                            <el-form-item label="生成结果">
                                <el-input type="textarea" :rows="6" :autosize="{ minRows: 4, maxRows: 8 }"
                                    :placeholder="generatedResult" resize="none" class="fixed-textarea" readonly />
                                <div class="flex items-center mt-1"> 
                                    <el-button type="success" size="small" round :icon="DocumentCopy"
                                        @click="copyToClipboard">
                                        复制
                                    </el-button>
                                    <div class="text-sm text-green-600">
                                        长度: {{ generatedResult.length }} 个字符
                                    </div>
                                </div>
                            </el-form-item>

                            <!-- 生成按钮 -->
                            <el-form-item>
                                <el-button type="primary" :loading="generating" @click="generateStringHandler"
                                    class="w-full bg-blue-600 hover:bg-blue-700" size="large">
                                    <template #icon>
                                        <el-icon>
                                            <MagicStick />
                                        </el-icon>
                                    </template>
                                    生成字符串
                                </el-button>
                            </el-form-item>
                        </el-form>


                    </el-card>
                </div>

                <!-- 右侧：历史记录 -->
                <div class="col-span-2" style="height: 560px;">
                    <HistoryList @regenerate="handleRegenerate" />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { MagicStick, DocumentCopy } from '@element-plus/icons-vue'
import HistoryList from './StringHistoryList.vue'
import { generateString, getCharTypes } from '../services/api'
import { CHAR_TYPES } from '../utils/constants'

const form = reactive({
    length: 10,
    char_type: 'digits_letters',
    prefix: '',
    suffix: '',
    custom_chars: ''
})

const generating = ref(false)
const generatedResult = ref('')
// 双栏布局下始终显示历史
const charTypes = ref(CHAR_TYPES)

// 获取支持的字符类型
onMounted(async () => {
    try {
        const types = await getCharTypes()
        charTypes.value = types
    } catch (error) {
        console.error('获取字符类型失败:', error)
    }
})

// 生成字符串
const generateStringHandler = async () => {
    if (!validateForm()) return

    generating.value = true
    try {
        const response = await generateString(form)
        generatedResult.value = response.result
        ElMessage.success('字符串生成成功！')

        // 刷新历史记录
        // 通过事件总线或其他方式通知 HistoryList 刷新
        window.dispatchEvent(new CustomEvent('history-updated'))
    } catch (error) {
        // 全局拦截器已提示，这里无需重复弹窗
    } finally {
        generating.value = false
    }
}

// 表单验证
const validateForm = () => {
    if (form.length <= 0) {
        ElMessage.warning('请输入有效的字符串长度')
        return false
    }

    if (form.char_type === 'custom' && !form.custom_chars) {
        ElMessage.warning('自定义字符类型需要提供字符集')
        return false
    }

    const prefixSuffixLength = form.prefix.length + form.suffix.length
    if (prefixSuffixLength > form.length) {
        ElMessage.warning('前缀和后缀的总长度不能超过字符串总长度')
        return false
    }

    return true
}

// 复制到剪贴板
const copyToClipboard = async () => {
    try {
        await navigator.clipboard.writeText(generatedResult.value)
        ElMessage.success('已复制到剪贴板')
    } catch (err) {
        // 降级方案
        const textArea = document.createElement('textarea')
        textArea.value = generatedResult.value
        document.body.appendChild(textArea)
        textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
        ElMessage.success('已复制到剪贴板')
    }
}

// 重新生成历史记录中的项目
const handleRegenerate = (history) => {
    form.length = history.length
    form.char_type = history.char_type
    form.prefix = history.prefix || ''
    form.suffix = history.suffix || ''
    form.custom_chars = history.custom_chars || ''

    // 滚动到顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })

    // 自动生成
    setTimeout(() => {
        generateStringHandler()
    }, 100)
}
</script>

<style scoped>
:deep(.el-form-item__label) {
    font-weight: 600;
    color: #374151;
}

:deep(.el-card__header) {
    border-bottom: 1px solid #e5e7eb;
    padding: 20px;
}

.code-block {
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    background: #f8f9fa;
    padding: 12px;
    border-radius: 6px;
    border: 1px solid #e9ecef;
}
</style>